package com.radioapp.liaoliaobao.module.radio.publish;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.google.gson.Gson;
import com.jaydenxiao.common.base.BaseActivity;
import com.jaydenxiao.common.base.BaseRiggerFragment;
import com.jaydenxiao.common.commonutils.ToastUitl;
import com.jkb.fragment.rigger.rigger.Rigger;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.radioapp.liaoliaobao.R;
import com.radioapp.liaoliaobao.bean.ExpectBean;
import com.radioapp.liaoliaobao.bean.PayBean;
import com.radioapp.liaoliaobao.bean.address.AddressBean;
import com.radioapp.liaoliaobao.bean.appointment.DatingHopesBean;
import com.radioapp.liaoliaobao.bean.radio.RadioPublishBean;
import com.radioapp.liaoliaobao.constant.IntentConstant;
import com.radioapp.liaoliaobao.module.lifecyclerObserver.RxPermissionsFragmentObserver;
import com.radioapp.liaoliaobao.utils.AssetsUtils;
import com.radioapp.liaoliaobao.utils.BaiDuMapUtil;
import com.radioapp.liaoliaobao.utils.pay.PayUtil;
import com.radioapp.liaoliaobao.utils.timePicker.SelectImageUtils;
import com.radioapp.liaoliaobao.utils.timePicker.TimePickerCityUtil;
import com.radioapp.liaoliaobao.utils.timePicker.TimePickerDateUtil;
import com.radioapp.liaoliaobao.utils.timePicker.TimePickerOneUtil;
import com.radioapp.liaoliaobao.view.bgaphotopicker.BGASortableNinePhotoLayout;
import com.radioapp.liaoliaobao.view.dialog.more_select.MoreSelectDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.utils.LogUtils;

/**
 * 功能：发布电台
 * 描述
 * Created by yue on 2019-07-30
 */
public class RadioPublishFragment extends BaseRiggerFragment<RadioPublishView, RadioPublishPresenter> implements
        BGASortableNinePhotoLayout.Delegate, BaseActivity.ActivityResultByFragment,
        RxPermissionsFragmentObserver.PermissionCallBack, RadioPublishView, PayUtil.PayCallback {
    @BindView(R.id.tv_show)
    TextView tvShow;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_date)
    LinearLayout llDate;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.bga_ninePhotoLayout)
    BGASortableNinePhotoLayout mPhotosSnpl;
    @BindView(R.id.cbx_gender)
    CheckBox cbxGender;
    @BindView(R.id.cbx_comments)
    CheckBox cbxComments;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    RadioPublishBean radioPublishBean;

    private List<LocalMedia> selectList = new ArrayList<>();
    private ArrayList<LocalMedia> imagelist = new ArrayList<>();  //图片路径
    private List<String> paths = new ArrayList<>();//图片集合

    private RxPermissionsFragmentObserver rxPermissionsFragmentObserver;

    private boolean requestPermission = true;

    public List<String> times = new ArrayList<>(Arrays.asList("一整天", "上午", "中午", "下午", "晚上", "通宵"));


    private Integer provinceId; //省
    private Integer cityId; //城市
    private String mDate; //日期
    private String mTime;  //时间
    private String dating_time_str; //日期和时间合并
    BaiDuMapUtil gaoDeMapUtil;
    BDLocation mapLocation;

    private List<DatingHopesBean> datingHopesBeans;
    //本地的数据
    List<ExpectBean> expectBeans;
    private String dating_hopes;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_radio_pulish;
    }

    @Override
    public void handIntent(Bundle bundle) {
        super.handIntent(bundle);
        radioPublishBean = bundle.getParcelable(IntentConstant.RADIOPUBLISHBEAN);
        if (radioPublishBean != null) {
            initToolbar(radioPublishBean.getTitle(), true, false, null);
        }
    }

    @Override
    public void initView() {
        initToolbar(radioPublishBean.getTitle(), true, false, null);
        ((BaseActivity) mActivity).setActivityResultByFragment(this);

        //权限
        rxPermissionsFragmentObserver = new RxPermissionsFragmentObserver(this);
        getLifecycle().addObserver(rxPermissionsFragmentObserver);
        rxPermissionsFragmentObserver.setCallBack(this);
        rxPermissionsFragmentObserver.requestPermissions(0, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA);


        // 设置拖拽排序控件的代理
        mPhotosSnpl.setDelegate(this, 1);

        //请求期望
        // mPresenter.getDatingHopes();
        expectBeans = AssetsUtils.newInterface().expectBeans;


    }

    @Override
    public void tokenInvalidRefresh() {

    }


    @OnClick({R.id.ll_show, R.id.ll_address, R.id.ll_date, R.id.ll_time, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_show:  //显示约会期望
                if (datingHopesBeans != null) {
                    MoreSelectDialog.newInstance(datingHopesBeans, new MoreSelectConfirmClick()).
                            setMaxSelect(4).setTitle("约会期望").show(getChildFragmentManager(), "dialog");

                } else {
                    MoreSelectDialog.newInstance(expectBeans, new MoreSelectConfirmClick1()).
                            setMaxSelect(3).setTitle("约会期望").show(getChildFragmentManager(), "dialog");
                }
                break;
            case R.id.ll_address: //地区
                TimePickerCityUtil.newInterface().showPickerView(mActivity, 2, new TimePickerCityUtil.CitySelectListener() {
                    @Override
                    public void onSelected(AddressBean province, AddressBean.CitysBean citysBean,
                                           AddressBean.CitysBean.AreasBean areasBean) {
                        tvAddress.setText(province.getAreaName() + citysBean.getAreaName());
                        provinceId = province.getId();
                        cityId = citysBean.getId();
                    }
                });
                break;
            case R.id.ll_date: //日期
                TimePickerDateUtil.newInterface().showTimePicker(mActivity, "选择时间", new TimePickerDateUtil.DateSelectListener() {
                    @Override
                    public void onSelected(String date) {
                        mDate = date;
                        tvDate.setText(date);

                    }
                });
                break;
            case R.id.ll_time: //时间
                new TimePickerOneUtil().showPickerView(mActivity, "选择时间", times, new TimePickerOneUtil.SelectListener<String>() {
                    @Override
                    public void onSelected(String o) {
                        mTime = o;
                        tvTime.setText(o);
                    }
                });

                break;
            case R.id.tv_commit: //提交
                if (isFlag()) {
                    if (selectList != null && selectList.size() > 0) {
                        paths.clear();
                        for (LocalMedia media : selectList) {
                            String path;
                            if (media.isCut() && !media.isCompressed()) {
                                // 裁剪过
                                path = media.getCutPath();
                            } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                                path = media.getCompressPath();
                            } else {
                                // 原图
                                path = media.getPath();
                            }
                            paths.add(path);
                        }
                    }
                    //TODO 第一个参数可能是多个， 测试为了一个，等设计好了， 然后就是传多个参数
                    mPresenter.radioPublish(radioPublishBean.getId() + "", dating_hopes, provinceId, cityId,
                            mapLocation.getLongitude() + "", mapLocation.getLatitude() + "", mDate + mTime, etContent.getText().toString(),
                            cbxGender.isChecked() ? 1 : 0, cbxComments.isChecked() ? 0 : 1, paths);
                }

                break;
        }
    }


    public boolean isFlag() {
        if (TextUtils.isEmpty(dating_hopes)) {
            ToastUitl.showLong("请选择约会期望");
            return false;
        }
        if (provinceId == null || cityId == null) {
            ToastUitl.showLong("请选择约会地区");
            return false;
        }
        if (TextUtils.isEmpty(mDate)) {
            ToastUitl.showLong("请选择约会日期");
            return false;
        }
        if (TextUtils.isEmpty(mTime)) {
            ToastUitl.showLong("请选择约会时间");
            return false;
        }
        if (TextUtils.isEmpty(etContent.getText())) {
            ToastUitl.showLong("请输入内容");
            return false;
        }
        if (mapLocation == null) {
            ToastUitl.showLong("请打开GPS定位");
            return false;
        }
        return true;
    }


    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, List<LocalMedia> models, int clickPosition) {
        if (requestPermission) {
            SelectImageUtils.showALlImage(mActivity, imagelist, 9, PictureConfig.CHOOSE_REQUEST);
        } else {
            ToastUitl.showLong("请前往设置同意访问图片的权限");
        }


    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, List<LocalMedia> models, int clickPosition) {
        mPhotosSnpl.removeItem(position);
        for (int i = 0; i < selectList.size(); i++) {
            String path = "";
            if (selectList.get(i).isCut() && !selectList.get(i).isCompressed()) {
                // 裁剪过
                path = selectList.get(i).getCutPath();
            } else if (selectList.get(i).isCompressed() || (selectList.get(i).isCut() && selectList.get(i).isCompressed())) {
                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                path = selectList.get(i).getCompressPath();
            } else {
                // 原图
                path = selectList.get(i).getPath();
            }
            if (path.equals(model)) {
                selectList.remove(i);
                break;
            }
        }
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, List<LocalMedia> models, int clickPositon) {

    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, List<LocalMedia> models, int clickPosition) {

    }

    @Override
    public void onActivityResultByFragment(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    imagelist.clear();
                    for (LocalMedia media : selectList) {
                        imagelist.add(media);
                    }
                    mPhotosSnpl.setData(imagelist);
                    break;
            }
        }
    }

    /**
     * 百度地图定位
     */
    public void initBaiDu() {
        if (gaoDeMapUtil == null) {
            gaoDeMapUtil = BaiDuMapUtil.getInstance();
            gaoDeMapUtil.setContext(mActivity).setListener(new BaiDuMapUtil.GaoDeAMapLocationListener() {
                @Override
                public void onLocationChanged(BDLocation aMapLocation) {
                    mapLocation = aMapLocation;
                    LogUtils.e("获取纬度-->" + aMapLocation.getLatitude() + "经度" + aMapLocation.getLongitude());
                }

            });

            getLifecycle().addObserver(gaoDeMapUtil);
        }
    }

    @Override
    public void onSuccess() {
        if (isFlag()) {
            if (selectList != null && selectList.size() > 0) {
                paths.clear();
                for (LocalMedia media : selectList) {
                    String path;
                    if (media.isCut() && !media.isCompressed()) {
                        // 裁剪过
                        path = media.getCutPath();
                    } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                        // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                        path = media.getCompressPath();
                    } else {
                        // 原图
                        path = media.getPath();
                    }
                    paths.add(path);
                }
            }
            //TODO 第一个参数可能是多个， 测试为了一个，等设计好了， 然后就是传多个参数
            mPresenter.radioPublish(radioPublishBean.getId() + "", dating_hopes, provinceId, cityId,
                    mapLocation.getLongitude() + "", mapLocation.getLatitude() + "", mDate + mTime, etContent.getText().toString(),
                    cbxGender.isChecked() ? 1 : 0, cbxComments.isChecked() ? 1 : 0, paths);
        }
    }

    @Override
    public void onError() {

    }

    @Override
    public void onCancel() {

    }


    /**
     * 多选的接口回掉，约会期望(本地)
     */
    class MoreSelectConfirmClick1 implements MoreSelectDialog.OnConfirmClickListener<ExpectBean> {

        public void onClick(Set<ExpectBean> selectLists) {
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer stringhopes = new StringBuffer();
            String text = "";
            if (selectLists != null && selectLists.size() > 0) {
                for (ExpectBean list : selectLists) {
                    stringBuffer.append(list.getName()).append(",");
                    stringhopes.append(list.getId()).append(",");
                }
                if (stringBuffer.length() > 0) {
                    text = stringBuffer.substring(0, stringBuffer.length() - 1);
                    dating_hopes = stringhopes.substring(0, stringhopes.length() - 1);
                }
                tvShow.setText(text);
            }

        }
    }

    /**
     * 多选的接口回掉，约会期望
     */
    class MoreSelectConfirmClick implements MoreSelectDialog.OnConfirmClickListener<DatingHopesBean> {

        public void onClick(Set<DatingHopesBean> selectLists) {
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer stringhopes = new StringBuffer();
            String text = "";
            if (selectLists != null && selectLists.size() > 0) {
                for (DatingHopesBean list : selectLists) {
                    stringBuffer.append(list.getName()).append(",");
                    stringhopes.append(list.getId()).append(",");
                }
                if (stringBuffer.length() > 0) {
                    text = stringBuffer.substring(0, stringBuffer.length() - 1);
                    dating_hopes = stringhopes.substring(0, stringhopes.length() - 1);
                }
                tvShow.setText(text);
            }

        }
    }

    @Override
    public void getDatingHopes(List<DatingHopesBean> datingHopesBeans) {
        this.datingHopesBeans = datingHopesBeans;
    }

    @Override
    public void success() {
        ToastUitl.showLong("发布成功");
        Rigger.getRigger(this).close();

    }

    @Override
    public void pay(PayBean payBean) {
        PayUtil.getInstance().Pay(mActivity, 2, payBean.getAppid(),new Gson().toJson(payBean), this);
    }

    @Override
    public void granted(int type) {
        initBaiDu();
        requestPermission = true;
    }

    @Override
    public void shouldShowRequestPermissionRationale() {
        requestPermission = false;
    }

    @Override
    public void other() {
        requestPermission = false;
    }


}
